from django.db import models
from django.utils import timezone

class Platform(models.Model):
    """监控平台表"""
    name = models.CharField(verbose_name="平台名称", max_length=50)
    icon = models.CharField(verbose_name="平台图标", max_length=200, null=True, blank=True)
    api_url = models.CharField(verbose_name="API地址", max_length=255, null=True, blank=True)
    is_active = models.BooleanField(verbose_name="是否启用", default=True)
    created_at = models.DateTimeField(verbose_name="创建时间", auto_now_add=True)
    updated_at = models.DateTimeField(verbose_name="更新时间", auto_now=True)

    class Meta:
        verbose_name = "监控平台"
        verbose_name_plural = "监控平台"
        ordering = ['-created_at']

    def __str__(self):
        return self.name

class Keyword(models.Model):
    """关键词表"""
    word = models.CharField(verbose_name="关键词", max_length=50)
    weight = models.IntegerField(verbose_name="权重", default=1)
    is_active = models.BooleanField(verbose_name="是否启用", default=True)
    created_at = models.DateTimeField(verbose_name="创建时间", auto_now_add=True)
    updated_at = models.DateTimeField(verbose_name="更新时间", auto_now=True)

    class Meta:
        verbose_name = "关键词"
        verbose_name_plural = "关键词"
        ordering = ['-weight']

    def __str__(self):
        return self.word

class SentimentData(models.Model):
    """舆情数据表"""
    SENTIMENT_CHOICES = (
        (1, "正面"),
        (0, "中性"),
        (-1, "负面"),
    )
    
    title = models.CharField(verbose_name="标题", max_length=255)
    content = models.TextField(verbose_name="内容")
    url = models.URLField(verbose_name="原文链接", max_length=255)
    platform = models.ForeignKey(verbose_name="来源平台", to="Platform", on_delete=models.CASCADE)
    sentiment_value = models.FloatField(verbose_name="情感值", default=0)  # 情感值范围：-1.0 ~ 1.0
    sentiment_type = models.SmallIntegerField(verbose_name="情感类型", choices=SENTIMENT_CHOICES, default=0)
    heat_value = models.IntegerField(verbose_name="热度值", default=0)
    publish_time = models.DateTimeField(verbose_name="发布时间")
    created_at = models.DateTimeField(verbose_name="采集时间", auto_now_add=True)
    
    # 关联关键词，多对多关系
    keywords = models.ManyToManyField(to="Keyword", through="SentimentKeywordRelation")

    class Meta:
        verbose_name = "舆情数据"
        verbose_name_plural = "舆情数据"
        ordering = ['-publish_time']
        indexes = [
            models.Index(fields=['publish_time']),
            models.Index(fields=['sentiment_type']),
            models.Index(fields=['heat_value']),
        ]

    def __str__(self):
        return self.title
    
    def save(self, *args, **kwargs):
        """根据情感值设置情感类型"""
        if self.sentiment_value > 0.3:
            self.sentiment_type = 1  # 正面
        elif self.sentiment_value < -0.3:
            self.sentiment_type = -1  # 负面
        else:
            self.sentiment_type = 0  # 中性
        super().save(*args, **kwargs)

class SentimentKeywordRelation(models.Model):
    """舆情数据与关键词的关联表"""
    sentiment = models.ForeignKey(verbose_name="舆情数据", to="SentimentData", on_delete=models.CASCADE)
    keyword = models.ForeignKey(verbose_name="关键词", to="Keyword", on_delete=models.CASCADE)
    frequency = models.IntegerField(verbose_name="出现频次", default=1)
    
    class Meta:
        verbose_name = "舆情关键词关联"
        verbose_name_plural = "舆情关键词关联"
        unique_together = ['sentiment', 'keyword']

class MonitorTarget(models.Model):
    """监控目标表"""
    TYPE_CHOICES = (
        (1, "企业"),
        (2, "人物"),
        (3, "事件"),
        (4, "其他"),
    )
    
    name = models.CharField(verbose_name="名称", max_length=100)
    type = models.SmallIntegerField(verbose_name="类型", choices=TYPE_CHOICES, default=1)
    image = models.CharField(verbose_name="图片", max_length=255, null=True, blank=True)
    description = models.TextField(verbose_name="描述", null=True, blank=True)
    is_priority = models.BooleanField(verbose_name="是否重点监控", default=False)
    created_at = models.DateTimeField(verbose_name="创建时间", auto_now_add=True)
    updated_at = models.DateTimeField(verbose_name="更新时间", auto_now=True)
    
    # 关联关键词，表示这个监控目标关注哪些关键词
    keywords = models.ManyToManyField(to="Keyword", related_name="targets")

    class Meta:
        verbose_name = "监控目标"
        verbose_name_plural = "监控目标"
        ordering = ['-is_priority', '-created_at']

    def __str__(self):
        return self.name

class AlertRule(models.Model):
    """预警规则表"""
    name = models.CharField(verbose_name="规则名称", max_length=100)
    target = models.ForeignKey(verbose_name="监控目标", to="MonitorTarget", on_delete=models.CASCADE)
    condition_type = models.CharField(verbose_name="条件类型", max_length=50)  # 如 sentiment_negative, keyword_frequency 等
    threshold = models.FloatField(verbose_name="阈值")
    time_window = models.IntegerField(verbose_name="时间窗口(分钟)")
    is_active = models.BooleanField(verbose_name="是否启用", default=True)
    created_at = models.DateTimeField(verbose_name="创建时间", auto_now_add=True)
    updated_at = models.DateTimeField(verbose_name="更新时间", auto_now=True)

    class Meta:
        verbose_name = "预警规则"
        verbose_name_plural = "预警规则"
        ordering = ['-created_at']

    def __str__(self):
        return self.name

class AlertLog(models.Model):
    """预警日志表"""
    rule = models.ForeignKey(verbose_name="触发规则", to="AlertRule", on_delete=models.CASCADE)
    trigger_value = models.FloatField(verbose_name="触发值")
    is_handled = models.BooleanField(verbose_name="是否已处理", default=False)
    triggered_at = models.DateTimeField(verbose_name="触发时间", default=timezone.now)
    handled_at = models.DateTimeField(verbose_name="处理时间", null=True, blank=True)
    
    # 关联触发这条预警的舆情数据
    sentiments = models.ManyToManyField(to="SentimentData", related_name="alerts")

    class Meta:
        verbose_name = "预警日志"
        verbose_name_plural = "预警日志"
        ordering = ['-triggered_at']

    def __str__(self):
        return f"{self.rule.name}_{self.triggered_at.strftime('%Y%m%d%H%M%S')}"

class SystemStatus(models.Model):
    """系统状态表"""
    name = models.CharField(verbose_name="服务名称", max_length=50)
    type = models.CharField(verbose_name="服务类型", max_length=50)  # 如 crawler, nlp, api 等
    status = models.BooleanField(verbose_name="运行状态", default=True)
    response_time = models.IntegerField(verbose_name="响应时间(ms)", default=0)
    last_check = models.DateTimeField(verbose_name="最后检查时间", auto_now=True)
    description = models.CharField(verbose_name="描述", max_length=255, null=True, blank=True)

    class Meta:
        verbose_name = "系统状态"
        verbose_name_plural = "系统状态"
        ordering = ['type', 'name']

    def __str__(self):
        return self.name

class DailyStatistics(models.Model):
    """每日统计数据表"""
    date = models.DateField(verbose_name="日期", unique=True)
    total_count = models.IntegerField(verbose_name="舆情总量", default=0)
    positive_count = models.IntegerField(verbose_name="正面舆情数", default=0)
    neutral_count = models.IntegerField(verbose_name="中性舆情数", default=0)
    negative_count = models.IntegerField(verbose_name="负面舆情数", default=0)
    alert_count = models.IntegerField(verbose_name="预警次数", default=0)
    created_at = models.DateTimeField(verbose_name="创建时间", auto_now_add=True)
    updated_at = models.DateTimeField(verbose_name="更新时间", auto_now=True)

    class Meta:
        verbose_name = "每日统计"
        verbose_name_plural = "每日统计"
        ordering = ['-date']

    def __str__(self):
        return str(self.date)
